import { Node, Sprite, SpriteFrame, Texture2D, Vec3, _decorator } from 'cc';
import { XLoader } from './XLoader';
const { ccclass, property } = _decorator;

@ccclass('XBitmap')
export class XBitmap extends Node {

    private _sprite: Sprite;
    private _position: Vec3 = new Vec3();

    constructor() {
        super();
        //
        this.addComponent(Sprite);
        this._sprite = this.getComponent(Sprite);
    }

    destroy(): boolean {
        if (this._sprite) {
            this._sprite.spriteFrame.decRef();
            this._sprite.spriteFrame = null;
        }
        return super.destroy();
    }

    public set sourceWithSpriteFrame(path: string) {
        XLoader.loadSpriteframe(`${path}/spriteFrame`, (content: SpriteFrame) => {
            this._sprite.spriteFrame = content;
            content.addRef();
        }, this);
    }

    public set sourceWithTexture(path: string) {
        XLoader.loadTexture(`${path}/texture`, (texture: Texture2D) => {
            const content = new SpriteFrame();
            content.texture = texture;
            this._sprite.spriteFrame = content;
            //
            content.addRef();
        }, this);
    }

    public get x(): number {
        return this.getPosition(this._position).x;
    }

    public set x(val: number) {
        this.setPosition(val, this.y, 0);
    }

    public get y(): number {
        return this.getPosition(this._position).y;
    }

    public set y(val: number) {
        this.setPosition(this.x, val, 0);
    }

    public set visible(val: boolean) {
        this._sprite.enabled = val;
    }
}

